<template>
  <div class="profile-edit-page">
    <div class="profile-edit-container">
      <div class="page-header">
        <h2>编辑个人资料</h2>
        <a-button @click="handleBack" ghost>
          <template #icon><arrow-left-outlined /></template>
          返回
        </a-button>
      </div>

      <a-card class="profile-form-card">
        <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" @finish="handleSubmit">
          <!-- 头像上传区域 -->
          <a-form-item label="头像" name="avatar">
            <div class="avatar-upload-section">
              <a-upload :show-upload-list="false" :before-upload="beforeUpload" :custom-request="handleAvatarUpload" accept="image/*">
                <div class="avatar-upload-wrapper">
                  <a-avatar :size="120" :src="avatarUrl" class="profile-avatar-large" :style="{ backgroundColor: avatarUrl ? 'transparent' : '#1890ff' }">
                    {{ formData.username?.charAt(0)?.toUpperCase() || 'U' }}
                  </a-avatar>
                  <div class="avatar-upload-overlay">
                    <camera-outlined class="upload-icon" />
                    <span class="upload-text">点击上传头像</span>
                  </div>
                  <a-spin :spinning="avatarUploading" class="avatar-loading" />
                </div>
              </a-upload>
              <div class="avatar-tips">
                <p>支持 JPG、PNG 格式，建议尺寸 200x200px，文件大小不超过 2MB</p>
              </div>
            </div>
          </a-form-item>

          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="用户名" name="username">
                <a-input v-model:value="formData.username" placeholder="请输入用户名" :maxlength="20" size="large" />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="开始工作日期" name="work_start_date">
                <a-date-picker v-model:value="workStartDate" placeholder="选择开始工作日期" style="width: 100%" size="large" :disabledDate="disabledDate" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="职业方向" name="career_direction">
                <a-select v-model:value="formData.career_direction" placeholder="请选择职业方向" :options="careerOptions" size="large" allowClear />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="职位" name="position">
                <a-input v-model:value="formData.position" placeholder="请输入职位" :maxlength="50" size="large" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="公司" name="company">
            <a-input v-model:value="formData.company" placeholder="请输入公司名称" :maxlength="100" size="large" />
          </a-form-item>

          <a-form-item label="个人介绍" name="bio">
            <a-textarea v-model:value="formData.bio" placeholder="简单介绍一下自己..." :rows="6" :maxlength="500" show-count size="large" />
          </a-form-item>

          <a-form-item label="兴趣标签" name="interest_tags">
            <div class="interest-tags-section">
              <div class="interest-tags">
                <a-tag v-for="(tag, index) in formData.interest_tags" :key="index" closable @close="removeTag(index)" class="tag-item" size="large">
                  {{ tag }}
                </a-tag>

                <a-input v-if="tagInputVisible" ref="tagInputRef" v-model:value="tagInputValue" @blur="handleTagInputConfirm" @keyup.enter="handleTagInputConfirm" placeholder="输入标签" class="tag-input" size="small" />

                <a-tag v-else @click="showTagInput" class="add-tag" size="large"> <plus-outlined /> 添加标签 </a-tag>
              </div>
              <p class="tag-tips">最多可添加10个标签</p>
            </div>
          </a-form-item>

          <a-form-item>
            <div class="form-actions">
              <a-button @click="handleBack" size="large">取消</a-button>
              <a-button type="primary" html-type="submit" :loading="loading" size="large"> 保存资料 </a-button>
            </div>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { ArrowLeftOutlined, CameraOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { getToken } from '@/utils/auth'
import { getImageUrl } from '@/utils/image'
import { useUserStore } from '@/stores/user'
import dayjs from 'dayjs'
import { API_BASE_URL } from '@/utils/api'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const formRef = ref()
const loading = ref(false)
const avatarUploading = ref(false)
const tagInputVisible = ref(false)
const tagInputRef = ref()
const tagInputValue = ref('')

// 表单数据
const formData = ref({
  username: '',
  avatar: '',
  work_start_date: '',
  career_direction: '',
  position: '',
  company: '',
  bio: '',
  interest_tags: []
})

// 头像URL处理
const avatarUrl = computed(() => {
  return formData.value.avatar ? getImageUrl(formData.value.avatar) : ''
})

// 工作开始日期处理
const workStartDate = computed({
  get: () => {
    return formData.value.work_start_date ? dayjs(formData.value.work_start_date) : null
  },
  set: (val) => {
    formData.value.work_start_date = val ? val.format('YYYY-MM-DD') : ''
  }
})

// 禁用未来日期
const disabledDate = (current) => {
  return current && current > dayjs().endOf('day')
}

// 职业方向选项
const careerOptions = [
  { label: '前端开发', value: '前端开发' },
  { label: '后端开发', value: '后端开发' },
  { label: '全栈开发', value: '全栈开发' },
  { label: '移动端开发', value: '移动端开发' },
  { label: 'UI/UX设计', value: 'UI/UX设计' },
  { label: '产品经理', value: '产品经理' },
  { label: '测试工程师', value: '测试工程师' },
  { label: '运维工程师', value: '运维工程师' },
  { label: '数据分析师', value: '数据分析师' },
  { label: '算法工程师', value: '算法工程师' },
  { label: '架构师', value: '架构师' },
  { label: '技术管理', value: '技术管理' },
  { label: '其他', value: '其他' }
]

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  position: [{ max: 50, message: '职位长度不能超过50个字符', trigger: 'blur' }],
  company: [{ max: 100, message: '公司名称长度不能超过100个字符', trigger: 'blur' }],
  bio: [{ max: 500, message: '个人介绍长度不能超过500个字符', trigger: 'blur' }]
}

// 获取用户资料数据
const fetchUserProfile = async () => {
  try {
    const headers = {}
    if (getToken()) {
      headers.Authorization = `Bearer ${getToken()}`
    }

    const response = await fetch(`${API_BASE_URL}/auth/profile/${userStore.user.userId}`, { headers })
    const result = await response.json()

    if (result.code === 200) {
      formData.value = {
        username: result.data.username || '',
        avatar: result.data.avatar || '',
        work_start_date: result.data.work_start_date || '',
        career_direction: result.data.career_direction || '',
        position: result.data.position || '',
        company: result.data.company || '',
        bio: result.data.bio || '',
        interest_tags: [...(result.data.interest_tags || [])]
      }
    } else {
      message.error('获取个人资料失败')
      handleBack()
    }
  } catch (error) {
    console.error('获取个人资料失败:', error)
    message.error('网络错误，请稍后重试')
    handleBack()
  }
}

// 头像上传前验证
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarUpload = async ({ file }) => {
  try {
    avatarUploading.value = true

    const formDataUpload = new FormData()
    formDataUpload.append('image', file)

    const response = await fetch(`${API_BASE_URL}/upload/avatar`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${getToken()}`
      },
      body: formDataUpload
    })

    const result = await response.json()

    if (result.code === 200) {
      formData.value.avatar = result.data.filename
      message.success('头像上传成功')
    } else {
      message.error(result.msg || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    message.error('头像上传失败，请稍后重试')
  } finally {
    avatarUploading.value = false
  }
}

// 显示标签输入框
const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

// 确认添加标签
const handleTagInputConfirm = () => {
  const inputValue = tagInputValue.value.trim()

  if (inputValue && !formData.value.interest_tags.includes(inputValue)) {
    if (formData.value.interest_tags.length >= 10) {
      message.warning('最多只能添加10个标签')
    } else {
      formData.value.interest_tags.push(inputValue)
    }
  }

  tagInputVisible.value = false
  tagInputValue.value = ''
}

// 移除标签
const removeTag = (index) => {
  formData.value.interest_tags.splice(index, 1)
}

// 处理表单提交
const handleSubmit = async () => {
  try {
    loading.value = true

    const response = await fetch(`${API_BASE_URL}/auth/profile`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${getToken()}`
      },
      body: JSON.stringify(formData.value)
    })

    const result = await response.json()

    if (result.code === 200) {
      message.success('个人资料更新成功')

      // 更新用户store中的用户信息
      userStore.setUser({
        ...userStore.user,
        username: formData.value.username,
        avatar: formData.value.avatar
      })

      // 返回用户中心
      router.push(`/user/${userStore.user.userId}`)
    } else {
      message.error(result.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新个人资料失败:', error)
    message.error('更新失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 返回上一页
const handleBack = () => {
  router.go(-1)
}

// 页面加载时获取用户资料
onMounted(() => {
  if (!userStore.isAuthenticated) {
    message.warning('请先登录')
    router.push('/articles')
    return
  }

  fetchUserProfile()
})
</script>

<style scoped>
.profile-edit-page {
  background: #f5f5f5;
  min-height: 100vh;
  padding: 24px;
}

.profile-edit-container {
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
}

.profile-form-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.avatar-upload-section {
  width: 80px;
  height: 80px;
  overflow: hidden;
  text-align: center;
}

.avatar-upload-wrapper {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.profile-avatar-large {
  border: 4px solid #f0f0f0;
  transition: all 0.3s;
}

.avatar-upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  color: white;
}

.avatar-upload-wrapper:hover .avatar-upload-overlay {
  opacity: 1;
}

.avatar-upload-wrapper:hover .profile-avatar-large {
  border-color: #1890ff;
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 12px;
}

.avatar-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
}

.avatar-tips {
  margin-top: 16px;
}

.avatar-tips p {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.interest-tags-section {
  width: 100%;
}

.interest-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  margin-bottom: 8px;
}

.tag-item {
  margin: 0;
  user-select: none;
}

.tag-input {
  width: 120px;
}

.add-tag {
  cursor: pointer;
  border-style: dashed;
  background: #fafafa;
  border-color: #d9d9d9;
  color: #666;
  margin: 0;
  transition: all 0.3s;
}

.add-tag:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.tag-tips {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 32px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 600;
  font-size: 16px;
}

:deep(.ant-input),
:deep(.ant-select-selector),
:deep(.ant-picker) {
  border-radius: 8px;
}

:deep(.ant-input:focus),
:deep(.ant-input-focused) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

:deep(.ant-select:focus .ant-select-selector),
:deep(.ant-select-focused .ant-select-selector) {
  border-color: #1890ff !important;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
}

@media (max-width: 768px) {
  .profile-edit-page {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .profile-avatar-large {
    width: 100px !important;
    height: 100px !important;
  }

  .form-actions {
    flex-direction: column;
  }
}
</style>
